package com.imooc.imoocbilibili.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.imoocbilibili.entity.User;
import com.imooc.imoocbilibili.entity.UserMoments;
import com.imooc.imoocbilibili.interceptor.ThreadUser;
import com.imooc.imoocbilibili.mapper.UserMomentsMapper;
import com.imooc.imoocbilibili.service.UserFollowingService;
import com.imooc.imoocbilibili.service.UserMomentsService;
import com.imooc.imoocbilibili.task.UserMomentsTask;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("userMomentsService")
@RequiredArgsConstructor
public class UserMomentsServiceImpl extends ServiceImpl<UserMomentsMapper, UserMoments> implements UserMomentsService {
    private final UserMomentsTask userMomentsTask;
    private final StringRedisTemplate redisTemplate;

    @Override
    public Page<UserMoments> queryPage(Integer pageNo, Integer pageSize) {
        Page<UserMoments> page = this.page(
                new Page<>(pageNo, pageSize),
                // 拼接查询条件
                new LambdaQueryWrapper<UserMoments>()
        );
        return page;
    }

    @Override
    public void addUserMoments(UserMoments userMoments) {
        User user = ThreadUser.getUser();
        userMoments.setUserid(user.getId());
        userMoments.setCreatetime(new Date());
        this.save(userMoments);
        // 给粉丝发送动态
        userMomentsTask.pushUserMomentsTaskToFans(userMoments);
    }

    @Override
    public List<UserMoments> getUserMoments() {
        User user = ThreadUser.getUser();
        Long userId = user.getId();
        String key = "subscribed-" + userId;
        String subscribedListStr = redisTemplate.opsForValue().get(key);
        return JSONUtil.toList(subscribedListStr, UserMoments.class);
    }

}